package com.coffee.web.utils;

import com.alibaba.fastjson.JSONObject;
import com.coffee.core.enums.ExceptionEnum;
import com.coffee.core.exception.BusinessException;
import com.coffee.core.util.HttpClientUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.Map;
import java.util.SortedMap;
import java.util.TreeMap;


@Slf4j
@Component
public class WeixinGzhAppletsUtil {


    public static String appId = "wxf85ea2f973a0970d";

    public static String gzhAppId = "wx4eee7ccfcf276d4c";

    public static String gzhAppSecret = "f152d2609e9869646f5127e78a5d9c8f";

    public static String appSecret = "e79bcca19edd1572167fb706f12e4a53";

    @Value("${parameter.weixin.appId}")
    private void setAppId(String appIdStr) {
        appId = appIdStr;
    }

    @Value("${parameter.weixin.gzhAppId}")
    private void setGzhAppId(String gzhAppIdStr) {
        gzhAppId = gzhAppIdStr;
    }

    @Value("${parameter.weixin.gzhAppSecret}")
    private void setGzhAppSecret(String gzhAppSecretStr) {
        gzhAppSecret = gzhAppSecretStr;
    }

    @Value("${parameter.weixin.appSecret}")
    private void setMchId(String appSecretStr) {
        appSecret = appSecretStr;
    }

    public static void main(String[] args) throws BusinessException {
        System.out.println(getAccessToken());
    }


    public static JSONObject getAccessToken() throws BusinessException {
        try {
            String ret = HttpClientUtil.get("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" + appId + "&secret=" + appSecret);
            log.info("获取accessToken=" + ret);
            JSONObject jsonObject = JSONObject.parseObject(ret);
            Integer errcode = jsonObject.getInteger("errcode");
            if (errcode == null) {
                return jsonObject;
            } else {
                throw new BusinessException(errcode, jsonObject.getString("errmsg"));
            }
        } catch (Exception e) {
            e.printStackTrace();
            throw new BusinessException(ExceptionEnum.ERROR_9999.getCode(), "Exception");
        }
    }

    public static JSONObject getGzhAccessToken() throws BusinessException {
        try {
            String ret = HttpClientUtil.get("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" + gzhAppId + "&secret=" + gzhAppSecret);
            log.info("获取accessToken=" + ret);
            JSONObject jsonObject = JSONObject.parseObject(ret);
            Integer errcode = jsonObject.getInteger("errcode");
            if (errcode == null) {
                return jsonObject;
            } else {
                throw new BusinessException(errcode, jsonObject.getString("errmsg"));
            }
        } catch (Exception e) {
            e.printStackTrace();
            throw new BusinessException(ExceptionEnum.ERROR_9999.getCode(), "Exception");
        }
    }


    public static JSONObject sendMessage(String accessToken, String openId, String templateId, String url, Map<String, Object> map) throws BusinessException {
        try {
            SortedMap<String, Object> parameters = new TreeMap<String, Object>();
            parameters.put("touser", openId);
            parameters.put("template_id", templateId);
            parameters.put("page", url);
            parameters.put("data", map);
            log.info("发送订阅消息参数=" + JSONObject.toJSONString(parameters));
            String ret = HttpClientUtil.doPostJson("https://api.weixin.qq.com/cgi-bin/message/subscribe/send?access_token=" + accessToken, JSONObject.toJSONString(parameters));
            log.info("发送订阅消息=" + ret);
            JSONObject jsonObject = JSONObject.parseObject(ret);
            Integer errcode = jsonObject.getInteger("errcode");
            if (errcode == null) {
                return null;
            } else {
                throw new BusinessException(errcode, jsonObject.getString("errmsg"));
            }
        } catch (Exception e) {
            e.printStackTrace();
            throw new BusinessException(ExceptionEnum.ERROR_9999.getCode(), "Exception");
        }
    }


    public static String push(String templateId, String token, String openid, Map<String, String> content, String url) throws BusinessException {
        String resultStatus = "0";//0:失败，1：成功
        try {
            //小程序统一消息推送
            String path = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=" + token;
            //封装参数
            JSONObject jsonData = new JSONObject();
            jsonData.put("touser", openid); // 小程序openid
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("appid", gzhAppId);// 公众号id
            jsonObject.put("template_id", templateId);// 公众号消息模板id
            JSONObject miniprogram = new JSONObject();
            miniprogram.put("appid", appId);
            miniprogram.put("page", url);
            jsonObject.put("miniprogram", miniprogram);
            //公众号消息数据封装
            JSONObject data = new JSONObject();
            data.put("first", getValue("你好,你的订单状态已修改"));//标题
            data.put("keyword1", getValue(content.get("inquireOrderId")));//设备编号
            data.put("keyword2", getValue(content.get("skuName")));//设备名称
            data.put("keyword3", getValue(content.get("status")));//设备地址
            data.put("keyword4", getValue(content.get("createTime")));//告警描述
            data.put("remark", getValue("请及时查看！"));
            jsonObject.put("data", data);
            jsonData.put("mp_template_msg", jsonObject);
            log.info("jsonData===" + JSONObject.toJSONString(jsonData));
            String s = HttpClientUtil.postBody(path, jsonData.toJSONString());
            log.info("公众号发送消息== =" + s);
            JSONObject jsonObject1 = JSONObject.parseObject(s);
            Integer errcode = jsonObject1.getInteger("errcode");
            if (errcode.equals(0)) {
                resultStatus = "1";
            } else if (errcode.equals(43004)) {
                resultStatus = "2";
            }
        } catch (Exception e) {
            log.error("微信公众号发送消息失败！", e.getMessage());
            resultStatus = "0";
        }
        return resultStatus;
    }

    private static JSONObject getValue(String value) {
        // TODO Auto-generated method stub
        JSONObject json = new JSONObject();
        json.put("value", value);
        json.put("color", "#173177");
        return json;
    }

}
